<?php

// 这是系统自动生成的公共文件
    function success($msg = '', $data = [], $code = 200)
    {
        $result = [
            'code' => $code,
            'msg' => $msg ?: 'success',
            'data' => $data,
        ];
        return response()->json($result);
    }

    function error($msg = '', $data = [], $code = 500)
    {
        $result = [
            'code' => $code,
            'msg' => $msg ?: 'error',
            'data' => $data,
        ];
        return response()->json($result);
    }

// 发送curl get请求
    function httpGetRequest($url, $data = [])
    {
        foreach ($data as $key => $value) {
            if (!is_string($value)) {
                $data[$key] = json_encode($value);
            }
        }

        $request_url = $url . '?' . http_build_query($data);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);
            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);
        return $response;
    }


    function httpPostRequest($url = '', $parameters = [], $common_parameters = [])
    {


        $parameters = json_encode($parameters);
        $request_url = $url . '?' . http_build_query($common_parameters);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            "Content-Type:application/json"
        ));
        $response = curl_exec($curl);
        if (curl_error($curl)) {
            $error_msg = curl_error($curl);
            $error_no = curl_errno($curl);
            curl_close($curl);
            throw new \Exception($error_msg, $error_no);
        }
        curl_close($curl);
        return $response;

    }

    function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8)
            . substr($chars, 8, 4)
            . substr($chars, 12, 4)
            . substr($chars, 16, 4)
            . substr($chars, 20, 12);
        return $uuid;
    }

    function validate_exception($msg = '参数错误', $code = 400)
    {
        abort($code, $msg);
    }

    /**
     * 采用递归将数据列表转换成树
     *
     * @param $dataArr           数据列表
     * @param int $rootId 根节点ID
     * @param string $pkName 主键名
     * @param string $pIdName 父节点id名
     * @param string $childName 子节点名称
     * @return array
     */
    function ListToTreeRecursive($dataArr, $rootId = 0, $pkName = 'id', $pIdName = 'pid', $childName = 'children')
    {
        $arr = [];
        foreach ($dataArr as $sorData) {
            if ($sorData[$pIdName] == $rootId) {
                $children = ListToTreeRecursive($dataArr, $sorData[$pkName]);
                if ($children) {
                    $sorData[$childName] = $children;
                } else {
                    $sorData[$childName] = [];
                }
                $arr[] = $sorData;
            }
        }

        return $arr;
    }

    function orderNumber()
    {
        return 'lt' . date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


    function get_client_ip($type = 0)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;

        if ($ip !== NULL) {
            return $ip[$type];
        }
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            //nginx 代理模式下，获取客户端真实IP
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            //客户端的ip
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            //浏览当前页面的用户计算机的网关
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            //浏览当前页面的用户计算机的ip地址
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    function downloadPic($url, $path)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        if (!file_exists($path)) {
            mkdir($path, 0777);
        }
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;

    }

    function getFilesize($num)
    {
        $p = 0;
        $format = 'bytes';
        if ($num > 0 && $num < 1024) {
            $p = 0;
            return number_format($num) . ' ' . $format;
        }
        if ($num >= 1024 && $num < pow(1024, 2)) {
            $p = 1;
            $format = 'KB';
        }
        if ($num >= pow(1024, 2) && $num < pow(1024, 3)) {
            $p = 2;
            $format = 'MB';
        }
        if ($num >= pow(1024, 3) && $num < pow(1024, 4)) {
            $p = 3;
            $format = 'GB';
        }
        if ($num >= pow(1024, 4) && $num < pow(1024, 5)) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 2) . ' ' . $format;
    }


/**
 * @param $price
 * @param int $multiple
 * @param int $float
 * @return string
 * 格式化价格
 */
function format_price($price, $multiple = 100, $float = 2)
{
    return number_format($price / $multiple, $float, '.', '');
}


/**
 * @param $amountYuan
 * @return int
 * 将元为单位的字符串转为以分记的整数
 */
function yuan_to_cent($amountYuan)
{
    return (int) ($amountYuan * 100);
}

function hidden_part($string, $leftLength = 1, $rightLength = 2)
{
    return mb_substr($string, 0, $leftLength) . ' **** ' . ($rightLength > 0 ? mb_substr($string, - $rightLength) : '');
}

function rand_number($id, $length = 12)
{
    return substr(rand(100000, 999999) . time() . $id . rand(1000, 9999), -$length);
}

/**
 * @param $path
 * @param string|null $disk
 * @return null|string
 */
function to_full_url($path, $disk = null)
{
    if(empty($path)) {
        return null;
    }

    // 如果字段本身就已经是完整的 url 就直接返回
    if (\Illuminate\Support\Str::startsWith($path, ['http://', 'https://'])) {
        return $path;
    }

    return \Storage::disk($disk ?? config('filesystems.default'))->url($path);
}

function to_full_urls($paths)
{
    return collect($paths)->map(function ($one) {
        return to_full_url($one);
    })->values();
}

/**
 * @param $path
 * @param null $disk
 * @return array
 * 转化为路径和url的格式
 */
function to_full_url_and_path($path, $disk = null)
{
    return [
        'path' => $path,
        'url' => to_full_url($path, $disk),
    ];
}

function to_full_url_and_paths($paths, $disk = null)
{
    return collect($paths)->map(function ($path) use ($disk) {
        return to_full_url_and_path($path, $disk);
    });
}

/**
 * @param $duration
 * @return string
 * 时长转化为展示用的格式
 */
function format_duration($duration)
{
    $hours = floor($duration / 3600);
    $minutes = floor(($duration / 60) % 60);
    $seconds = floor($duration % 60);

    return str_pad($hours, 2, 0, STR_PAD_LEFT) . ':' . str_pad($minutes, 2, 0, STR_PAD_LEFT) . ':' . str_pad($seconds, 2, 0, STR_PAD_LEFT);
}

/**
 * @param $options
 * @param string $keyFieldName
 * @param string $valueFieldName
 * @return array
 * 包裹 key => value 类型的选项为二维数组
 */
function wrap_options($options, $keyFieldName = 'key', $valueFieldName = 'value')
{
    return collect($options)
        ->map(function ($label, $key) use ($keyFieldName, $valueFieldName) {

            return [
                $keyFieldName => $key,
                $valueFieldName => $label,
            ];
        })
        ->values()
        ->toArray();
}


/**
 * @param array $array
 * @param string $glue
 * @return string
 * 将数组的key转为用指定符号链接的字符串
 */
function keys_to_string(array $array, $glue = ',')
{
    return implode($glue, array_keys($array));
}
